package service;

import model.Comment;
import dao.CommentDao;

import java.util.List;
import java.util.Map;

/**
 * 评论服务层
 */
public class CommentService {
    private CommentDao commentDao = new CommentDao();

    /**
     * 提交评论
     */
    public boolean submitComment(String content, int articleId, int userId) {
        if (content == null || content.trim().isEmpty()) {
            return false;
        }

        content = content.trim();

        if (content.length() > 500) {
            return false;
        }

        if (containsSensitiveWords(content)) {
            return false;
        }

        return commentDao.insertComment(content, articleId, userId);
    }

    /**
     * 获取文章的评论列表（带分页）
     */
    public List<Comment> getCommentsByArticle(int articleId, int page, int pageSize) {
        if (page < 1) page = 1;
        if (pageSize < 1) pageSize = 5;

        int offset = (page - 1) * pageSize;

        return commentDao.findByArticleId(articleId, pageSize, offset);
    }

    /**
     * 获取文章的评论分页信息
     */
    public Map<String, Object> getCommentPageInfo(int articleId, int pageSize) {
        int totalCount = commentDao.countByArticleId(articleId);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        Map<String, Object> pageInfo = new java.util.HashMap<>();
        pageInfo.put("totalCount", totalCount);
        pageInfo.put("totalPages", totalPages);
        pageInfo.put("currentPageSize", pageSize);

        return pageInfo;
    }

    /**
     * 获取文章的所有评论（不分页）
     */
    public List<Comment> getAllCommentsByArticle(int articleId) {
        return commentDao.findByArticleId(articleId, 1000, 0);
    }

    /**
     * 敏感词过滤
     */
    private boolean containsSensitiveWords(String content) {
        String[] sensitiveWords = {"fuck", "shit", "asshole", "脏话"};

        String lowerContent = content.toLowerCase();
        for (String word : sensitiveWords) {
            if (lowerContent.contains(word)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除评论
     */
    public boolean deleteComment(int commentId, int currentUserId) {
        return commentDao.deleteComment(commentId);
    }
}